#!/bin/bash
. lib.sh
. diff_time.sh
url_list="../m3u8下载信息/url_list.txt"
download_log="../m3u8下载信息/下载记录.txt"
string1="请输入下载链接："
string2="请输入文件名："
string3="请输入保存目录："
string4="其中有某项输入错误！"
string5="请检查后重试！"
string6="请选择输入方式："
string7="从文件获取"
string8="手动输入"
string9="请输入数字选择(留空退出)："
string10="输入错误，请重新输入！"
string11="正在下载"
string12="下载完成✅！"
string13="下载失败❌！"
string14="本次共输入"
string15="条下载链接"
string16="已存在，跳过下载！"
function date_now {
	date_log=$(date +"%Y-%m-%d %H:%M:%S")
}
function ffmpeg_install_termux {
	pkg_install ffmpeg
}
function ffmpeg_install_debian {
	apt_install ffmpeg
}
function read_p {
	read -p "$1" $2
}
function input_judgment {
	if [[ -n "$url" ]] && [[ -n "$name" ]] && [[ -n "$dir" ]] && [[ -d "$dir" ]];
	then
		download
	else
		echo -e "$string4\n$string5"
	fi
}
function output_state {
	date_now
	echo "$string14 $1 $string15 $date_log" > "$download_log"
}
function file_exist {
	if ! ls "$dir" | grep -q "$name";
	then
		input_judgment
	else
		date_now
		echo "$name $string16 $date_log" >> "$download_log"
	fi
}
function down_info_1 {
	mapfile -t array < "$url_list"
	output_state ${#array[@]}
	for i in "${!array[@]}"; do
		url=$(echo "${array[$i]}" | cut -d " " -f 1)
		name=$(echo "${array[$i]}" | cut -d " " -f 2)
		dir=$(echo "${array[$i]}" | cut -d " " -f 3)
		file_exist
	done
}
function down_info_2 {
	read_p "$string1" url
	read_p "$string2" name
	read_p "$string3" dir
	output_state 1
	file_exist
}
function download {
	date_now
	echo "$string11 $name.mp4 $date_log" >> "$download_log"
	start_str="$date_log"
	ffmpeg -i "$url" -c copy "$dir/$name.mp4"
	date_now
	end_str="$date_log"
	if [[ $? -eq 0 ]]; then
		echo "$name.mp4 $string12 $date_log" >> "$download_log"
		diff_time "$start_str" "$end_str" >> "$download_log"
	else
		echo "$name.mp4 $string13 $date_log" >> "$download_log"
	fi
}
function main {
	echo "$string6"
	echo -e "\n\
(1) $string7\n\
(2) $string8\n"
	read_p "$string9" number
	if [[ -z $number ]]; then
		exit 0
	fi
	while true; do
		case $number in
			1)
				down_info_1
				break
				;;
			2)
				down_info_2
				break
				;;
			*)
				echo "$string10"
		esac
	done
}
judgment "ffmpeg" ffmpeg_install_termux ffmpeg_install_debian
judgment_main "ffmpeg"
